package com.sky.controller.user;


import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result loginWeChat(@RequestBody UserLoginDTO dto) {

        //获取数据库中的数据（id，openid）
        User user = userService.loginWeChat(dto);

        UserLoginVO vo = new UserLoginVO();

        vo.setId(user.getId());
        vo.setOpenid(user.getOpenid());

        //一个微信用户只有一个openid，下面封装数据以便获取token
        HashMap map = new HashMap();  //生成的token参数要与解析的参数一致
        map.put(JwtClaimsConstant.USER_ID, user.getId());
        map.put("openid", user.getOpenid());
        //配置信息在配置文件和配置类中
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),map);
        //将token封装到返回对象中去
        vo.setToken(token);
        //返回vo对象给前端，携带数据用户id,openid,token
        return Result.success(vo);
    }


}
